package com.winning.pmph.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beust.jcommander.internal.Maps;
import com.winning.pmph.entity.*;
import com.winning.pmph.entity.IncreaseBook;
import com.winning.pmph.entity.IncreaseCategory;
import com.winning.pmph.entity.IncreaseResource;
import com.winning.pmph.entity.IncreaseResourceSub;
import com.winning.pmph.entity.KnowledgeLib;
import com.winning.pmph.entity.KnowledgeSyncStatus;
import com.winning.pmph.enumeration.KnowledgeSystem;
import com.winning.pmph.mapper.IncreaseBookMapper;
import com.winning.pmph.mapper.KnowledgeSyncStatusMapper;
import com.winning.pmph.utils.ApplicationContextUtil;
import com.winning.pmph.utils.ExecutorServiceFactory;
import com.winning.pmph.utils.HttpApi;
import com.winning.pmph.utils.PMPHAppUtil;
import com.winning.pmph.utils.RocketMQProducerUtil;
import com.winning.pmph.utils.UploadFileUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lbm
 * @since 2021-12-24
 */
@Service
public class IncreaseBookService extends ServiceImpl<IncreaseBookMapper, IncreaseBook> {
	@Autowired
	IncreaseCategoryService increaseCategoryService;
	@Autowired
	IncreaseResourceService increaseResourceService;
	@Autowired
	IncreaseResourceSubService increaseResourceSubService;
	@Autowired
	KnowledgeSyncStatusMapper knowledgeSyncStatusMapper;
	@Autowired
	KnowledgeSyncStatusService knowledgeSyncStatusService;

	public IncreaseBook editBook(IncreaseBook increaseBook) {
		if (StringUtils.isBlank(increaseBook.getId())) {
			return null;
		}
		
		//IncreaseBook book = this.getById(increaseBook.getId());
		Integer pubSourceType = increaseBook.getSourcePubType();
		//如果文档发布类型改为了加密，则推送一条数据到运维管理平台
		if(pubSourceType!=null && pubSourceType==1) {
			addIncreaseAip(increaseBook.getTopicNumber(),increaseBook.getBookName(),increaseBook.getIsbn());
		}
		increaseBook.setUpdateTime(new Date());
		this.updateById(increaseBook);
		return increaseBook;
	}
	
	public IncreaseBook deleteBook(IncreaseBook increaseBook) {
		if (StringUtils.isBlank(increaseBook.getId())) {
			return null;
		}
		increaseBook.setPubStatus(3);
		ExecutorServiceFactory.getInstance().submit(() -> {
        	syncBookData();
        });
		increaseBook.setUpdateTime(new Date());
		this.updateById(increaseBook);
		return increaseBook;
	}
	
	public void addIncreaseAip(String topicNumber, String bookName, String isbn) {
		String uri = ApplicationContextUtil.getProperty("increase_server") + "/increaseBook/addIncreaseAip";
		Map<String,String> params = new HashMap<>();
		params.put("topicNumber", topicNumber);
		params.put("bookName", bookName);
		if(StringUtils.isNotBlank(isbn)) {
			params.put("isbn", isbn);
		}
		JSONObject json = HttpApi.get(uri, params);
		System.out.println(json);
	}

	public boolean isPublish(String bookId) {
		if (StringUtils.isBlank(bookId)) {
			return false;
		}
		IncreaseBook book = this.getById(bookId);
		if(book==null) {
			return false;
		}
		if(book.getPubStatus()!=null && book.getPubStatus()==2) {
			return true;
		}
		return false;
	}

	public void uploadImg(MultipartFile multipartFile, String bookId) throws IOException {
		if (StringUtils.isBlank(bookId)) {
			return;
		}
		String path = "increasebook/";
		String savePath = ApplicationContextUtil.BASE_DOWN_FORDER + path;
		String name = UploadFileUtil.uploadFile(multipartFile, savePath, true);
		IncreaseBook book = new IncreaseBook();
		book.setId(bookId);
		book.setIndexImg("/" + path + name);
		this.baseMapper.updateById(book);
	}

	public void syncBookData() {
		String userName = PMPHAppUtil.getCurrentUserEnName();
        ExecutorServiceFactory.getInstance().submit(() -> {
        	syncBookData(userName,0);//增量推送数据
        });
	}

	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public void syncBookData(String userName, int isAllPush) {
		Date lastOpDate = null;
		QueryWrapper<KnowledgeSyncStatus> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("platform_id", "increase");
		queryWrapper.eq("knowledge_lib_id", "increasebook_lib_id");
		queryWrapper.orderByDesc("operated_time");
		queryWrapper.last("limit 1");
		List<KnowledgeSyncStatus> knowledgeSyncStatusList = knowledgeSyncStatusMapper.selectList(queryWrapper);

		if (knowledgeSyncStatusList != null && knowledgeSyncStatusList.size() > 0) {
			KnowledgeSyncStatus knowledgeSyncStatus = knowledgeSyncStatusList.get(0);
			if (knowledgeSyncStatus != null) {
				String opDate = knowledgeSyncStatus.getOperatedTime();
				if (opDate != null) {
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					try {
						lastOpDate = format.parse(opDate);
						Calendar calendar = Calendar.getInstance();
						calendar.setTime(lastOpDate);
						calendar.add(Calendar.HOUR, -14);
						lastOpDate= calendar.getTime();
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				System.out.println(opDate);
			}
		}
		System.out.println(lastOpDate);
		if (isAllPush == 1) {
			lastOpDate = null;
		}
		sendBookData(lastOpDate, userName);
		sendCateData(lastOpDate, userName);
		sendResourceData(lastOpDate, userName);
	}

	private void sendBookData(Date lastOpDate, String userName) {

		List<IncreaseBook> listBook = this.lambdaQuery().gt(lastOpDate != null, IncreaseBook::getUpdateTime, lastOpDate)
				.list();
		Map<String, String> syncDataMap = Maps.newHashMap();
		syncDataMap.put("syncPlatform", "increase");
		syncDataMap.put("userName", userName);
		syncDataMap.put("knowledgeLibId", KnowledgeLib.INCREASE_LIB_ID);
		listBook.forEach(item -> {
			JSONObject termObject = new JSONObject();
			termObject.put("type", KnowledgeSystem.INCREATE_BOOK.value);
			termObject.put("option", "add");
			termObject.put("data", item);
			boolean sendFlag2 = RocketMQProducerUtil.sendMessage("increase", "increasebook", item.getBookName(),
					JSON.toJSONString(termObject, SerializerFeature.WriteNullListAsEmpty,
							SerializerFeature.WriteNullStringAsEmpty));
			// 记录同步日志
			syncDataMap.put("knowledgeId", item.getId());
			knowledgeSyncStatusService.insertSync(syncDataMap, sendFlag2);
		});

	}
	
	public void sendDeleteBookData(String id, String userName) {
		IncreaseBook increaseBook = new IncreaseBook();
		increaseBook.setId(id);
		Map<String, String> syncDataMap = Maps.newHashMap();
		syncDataMap.put("syncPlatform", "increase");
		syncDataMap.put("userName", userName);
		syncDataMap.put("knowledgeLibId", KnowledgeLib.INCREASE_LIB_ID);
		JSONObject termObject = new JSONObject();
		termObject.put("type", KnowledgeSystem.INCREATE_BOOK.value);
		termObject.put("option", "delete");
		termObject.put("data", increaseBook);
		boolean sendFlag2 = RocketMQProducerUtil.sendMessage("increase", "increasebook", increaseBook.getBookName(),
				JSON.toJSONString(termObject, SerializerFeature.WriteNullListAsEmpty,
						SerializerFeature.WriteNullStringAsEmpty));
		// 记录同步日志
		syncDataMap.put("knowledgeId", increaseBook.getId());
		knowledgeSyncStatusService.insertSync(syncDataMap, sendFlag2);
	}

	private void sendCateData(Date lastOpDate, String userName) {

		List<IncreaseCategory> listCate = increaseCategoryService.lambdaQuery()
				.gt(lastOpDate != null, IncreaseCategory::getUpdateTime, lastOpDate).list();
		Map<String, String> syncDataMap = Maps.newHashMap();
		syncDataMap.put("knowledgeId", "increase");
		syncDataMap.put("syncPlatform", "increase");
		syncDataMap.put("userName", userName);
		syncDataMap.put("knowledgeLibId", KnowledgeLib.INCREASE_LIB_ID);
		listCate.forEach(item -> {
			JSONObject termObject = new JSONObject();
			termObject.put("type", KnowledgeSystem.INCREATE_CATE.value);
			termObject.put("option", "add");
			termObject.put("data", item);
			boolean sendFlag2 = RocketMQProducerUtil.sendMessage("increase", "increasebook", item.getName(),
					JSON.toJSONString(termObject, SerializerFeature.WriteNullListAsEmpty,
							SerializerFeature.WriteNullStringAsEmpty));
			// 记录同步日志
			syncDataMap.put("knowledgeId", item.getId());
			knowledgeSyncStatusService.insertSync(syncDataMap, sendFlag2);
		});

	}

	private void sendResourceData(Date lastOpDate, String userName) {

		List<IncreaseResource> list = increaseResourceService.lambdaQuery()
				.gt(lastOpDate != null, IncreaseResource::getUpdateTime, lastOpDate).list();
		Map<String, String> syncDataMap = Maps.newHashMap();
		syncDataMap.put("knowledgeId", "increase");
		syncDataMap.put("syncPlatform", "increase");
		syncDataMap.put("userName", userName);
		syncDataMap.put("knowledgeLibId", KnowledgeLib.INCREASE_LIB_ID);
		list.forEach(item -> {
			String resourceId = item.getId();
			List<IncreaseResourceSub> listSub = increaseResourceSubService.lambdaQuery().eq(IncreaseResourceSub::getResourceId, resourceId).list();
			item.setSubList(listSub);
			JSONObject termObject = new JSONObject();
			termObject.put("type", KnowledgeSystem.INCREATE_RESOURCE.value);
			termObject.put("option", "add");
			termObject.put("data", item);
			boolean sendFlag2 = RocketMQProducerUtil.sendMessage("increase", "increasebook", item.getName(),
					JSON.toJSONString(termObject, SerializerFeature.WriteNullListAsEmpty,
							SerializerFeature.WriteNullStringAsEmpty));
			// 记录同步日志
			syncDataMap.put("knowledgeId", item.getId());
			knowledgeSyncStatusService.insertSync(syncDataMap, sendFlag2);
		});

	}
	
	public static void main(String[] args) {
		String opDate = "2022-03-07 13:58:22";
		Date lastOpDate = null;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			lastOpDate = format.parse(opDate);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(lastOpDate);
			calendar.add(Calendar.HOUR, -14);
			lastOpDate= calendar.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		System.out.println(lastOpDate);
	}
}
